﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RLab.Visualization;
using System.Threading;
using RLab.Programming;

namespace rlab.presentation
{
    
    public partial class Main : Form
    {
        class ScaraObserver : IObserver<string>
        {
            private RichTextBox _box;
            public ScaraObserver( RichTextBox box )
            {
                _box = box;
            }

            public void OnCompleted()
            {
            }

            public void OnError( Exception error )
            {
            }

            private delegate void StringToUnitDelegate( string value ); // ;s

            public void OnNext( string value )
            {
                var objarr = new object[] { value };
                _box.BeginInvoke( new StringToUnitDelegate( Append ), objarr );
            }
            private void Append( object value )
            {
                _box.AppendText( value + "\n" );
            }
        }

        private Renderer r;
        private Scara s;
        ScaraObserver observer;



        public Main()
        {
            InitializeComponent();
            this.Load += new EventHandler( Main_Load );            
            this.KeyDown += new KeyEventHandler( Main_KeyDown );        
        }

        private void EvaluateText(string text)
        {            
            Evaluator.EvaluateAsync( text, s, observer );
        }

        void Main_Load( object sender, EventArgs e )
        {

        }

        internal bool InitializeGraphics()
        {
            try
            {
                r = new Renderer( renderPanel );

                s = ScaraModule.Create( r );

                observer = new ScaraObserver( logTxB );

                ( s as IProgrammable ).TraceEvent.Subscribe( observer );

                return true;
            }
            catch
            {
                return false;
            }
        }

        internal void Render()
        {
            r.Render();
        }

        private void Main_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyData == Keys.F5)
            {
                EvaluateFromEditor();
            }
        }

        private void button1_Click( object sender, EventArgs e )
        {
            EvaluateFromEditor();
        }

        private void EvaluateFromEditor()
        {
            logTxB.Clear();
            EvaluateText( editorTxB.Text );
        }
    }
}
